package cn.tedu.order.service;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private EasyIdClient easyIdClient;

    @Autowired
    private StorageClient storageClient;

    @Autowired
    private AccountClient accountClient;

    @Override
    @GlobalTransactional//开启全局事务，只在第一个模块添加
    @Transactional//控制本地事务
    public void create(Order order) {
        //TODO:远程调用发号器，获取订单id(全局唯一id发号器)
        String s = easyIdClient.nextId("order_business");
        Long orderId = Long.valueOf(s);
        order.setId(orderId);
        orderMapper.create(order);
        //TODO:调用库存，减少库存(远程调用服务)
        storageClient.decrease(order.getProductId(), order.getCount());
        //TODO：调用账户，减少金额(远程调用服务)
        accountClient.decrease(order.getUserId(), order.getMoney());
    }
}
